package com.kkd.kkdapp.activity;

import com.kkd.kkdapp.R;
import com.kkd.kkdapp.base.BaseActivity;
import com.kkd.kkdapp.db.CurUserModel;
import com.kkd.kkdapp.db.app.model.User;
import com.kkd.kkdapp.http.entity.PrivilegeData;
import com.kkd.kkdapp.http.manager.HttpCallBack;
import com.kkd.kkdapp.http.manager.KkdHttpMagager;
import com.kkd.kkdapp.utils.DialogUtils;
import com.kkd.kkdapp.utils.PreferenceUtils;
import com.kkd.kkdapp.utils.Tools;

import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

public class NicknameActivity extends BaseActivity implements OnClickListener {

	public static final int PRESERVATION_OK = 107;
	private final int UPDATANICKNAME_CODE_ZERO = 1;
	private final int UPDATANICKNAME_CODE_ELSE = 2;
	private RelativeLayout top_img; // 返回键
	private Button preservation_button; // 保存
	private RelativeLayout empty_bt; // 清除
	private EditText nickname_ed; // 输入框
	private TextView error_tv; // 异常提示
	private Dialog toLoadDialog; // 修改昵称等待Dialog
	private String updateDesc; // 修改昵称服务异常提示语

	private Handler mHandler = new Handler() {

		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case UPDATANICKNAME_CODE_ZERO:
				closeToLoadDialog();
				String nickName = nickname_ed.getText().toString();
				PreferenceUtils.getInstance().setNickname(
						NicknameActivity.this, nickName);
				setResult(PRESERVATION_OK);
				finish();
				break;
			case UPDATANICKNAME_CODE_ELSE:
				closeToLoadDialog();
				showToast(updateDesc);
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_nickname);
		initView();
		setListener();
	}

	/***
	 * 初始化控件
	 */
	public void initView() {
		top_img = (RelativeLayout) this.findViewById(R.id.top_img);
		nickname_ed = (EditText) this.findViewById(R.id.nickname_ed);
		empty_bt = (RelativeLayout) this.findViewById(R.id.empty_bt);
		error_tv = (TextView) findViewById(R.id.error_tv);
		preservation_button = (Button) this
				.findViewById(R.id.preservation_button);
		nickname_ed.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				int stLength = Tools.calculationStringLenght(s.toString());
				error_tv.setText("");
				preservation_button.setClickable(true);
				if (!TextUtils.isEmpty(s.toString())) {
					empty_bt.setVisibility(View.VISIBLE);
					preservation_button.setEnabled(true);
					if (stLength > 16) {
						error_tv.setText("超出最多输入限制");
						preservation_button.setEnabled(false);
						preservation_button.setClickable(false);
					} else if (stLength > 0 && stLength <= 16) {
						if (!Tools.judgeStringQualified(s.toString())) {
							error_tv.setText("昵称只能由数字、英文、中文、下划线组成");
							preservation_button.setEnabled(false);
							preservation_button.setClickable(false);
						}
					}
				} else {
					empty_bt.setVisibility(View.INVISIBLE);
					preservation_button.setEnabled(false);
					preservation_button.setClickable(false);
				}

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {

			}

			@Override
			public void afterTextChanged(Editable s) {

			}
		});
		// 手机号
		String phone = PreferenceUtils.getInstance().getPhone(this);
		// （设置&修改）昵称
		if (!PreferenceUtils.getInstance().getNickname(this).equals(phone)) {
			nickname_ed
					.setText(PreferenceUtils.getInstance().getNickname(this));
			nickname_ed.setSelection(nickname_ed.getText().toString().length());
		}

	}

	/***
	 * 注册监听事件
	 */
	public void setListener() {
		top_img.setOnClickListener(this);
		empty_bt.setOnClickListener(this);
		preservation_button.setOnClickListener(this);
		nickname_ed.setOnEditorActionListener(new OnEditorActionListener() {

			@Override
			public boolean onEditorAction(TextView v, int actionId,
					KeyEvent event) {
				if (actionId == EditorInfo.IME_ACTION_GO) {
					if (preservation_button.isClickable())
						updateNickNameInterface(nickname_ed.getText()
								.toString());
					return true;
				}
				return false;
			}
		});

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.top_img: // 返回键
			finish();
			break;
		case R.id.empty_bt: // 清除
			nickname_ed.setText("");
			break;
		case R.id.preservation_button: // 保存
			updateNickNameInterface(nickname_ed.getText().toString());
			break;
		}

	}

	@Override
	protected void onResume() {
		super.onResume();
		User user = CurUserModel.getCurUser();
		if (user == null || user.state != 0) { // 用户不为空且已登陆
			finish();
			return;
		}
		mHandler.postDelayed(new Runnable() {

			@Override
			public void run() {
				softKeyboard();
			}
		}, 101);

	}

	@Override
	protected void onPause() {
		super.onPause();
		softKeyboard();
	}

	/****
	 * 
	 * 修改用户昵称接口请求
	 * 
	 *****/
	public void updateNickNameInterface(String nickname) {
		showToLoadDialog("正在为您上传...");
		KkdHttpMagager.getInstance().updateNickName(nickname, String.class,
				new HttpCallBack() {

					@Override
					public void onSuccess(int statusCode, Object responseBody) {
						mHandler.sendEmptyMessage(UPDATANICKNAME_CODE_ZERO);
					}

					@Override
					public void onFailure(int statusCode, String desc) {
						NicknameActivity.this.updateDesc = desc;
						mHandler.sendEmptyMessage(UPDATANICKNAME_CODE_ELSE);
					}
				});

	}

	// 软键盘
	public void softKeyboard() {
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		// 得到InputMethodManager的实例
		if (imm.isActive()) {
			// 如果开启
			imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT,
					InputMethodManager.HIDE_NOT_ALWAYS);
			// 关闭软键盘，开启方法相同，这个方法是切换开启与关闭状态的
		}
	}

	// 等待
	public void showToLoadDialog(String content) {
		if (toLoadDialog != null) {
			toLoadDialog.cancel();
			toLoadDialog = null;
		}
		toLoadDialog = DialogUtils.toLoadDialog(this, content);
		toLoadDialog.show();
	}

	// 等待
	public void closeToLoadDialog() {
		if (toLoadDialog != null) {
			toLoadDialog.dismiss();
			toLoadDialog.cancel();
			toLoadDialog = null;
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (toLoadDialog != null) {
			toLoadDialog.cancel();
			toLoadDialog = null;
		}
	}

}
